package com.we.connect.weconnect.controller.system;

import com.we.connect.weconnect.model.common.ResultModel;
import com.we.connect.weconnect.model.system.SysUser;
import com.we.connect.weconnect.service.SysUserService;
import com.we.connect.weconnect.utils.RedisCache;
import com.we.connect.weconnect.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/system")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public String login(@ModelAttribute("sysUser") SysUser sysUser, Model model, HttpServletRequest request){
        if(sysUser.getUserName() == null || sysUser.getPassword() == null){
            model = ResultModel.fail("请填写用户名或者密码", "登录", "/login", model);
            return "common/tip";
        }

        SysUser user = sysUserService.loginSysUser(sysUser);
        if(null != user){
            UserUtils.setSysUser(request, "loginSysUser", user);
            return "redirect:/remind";
        }

        model = ResultModel.fail("登录失败", "登录", "/login", model);
        return "common/tip";
    }

    @PostMapping("/register")
    public String register(@ModelAttribute("sysUser") SysUser sysUser, Model model){
        if(sysUser.getUserName().equals("") || sysUser.getPassword().equals("") || sysUser.getEmail().equals("")){
            model = ResultModel.fail("未填写注册信息", "注册", "/register", model);
            return "common/tip";
        }

        Boolean isRegisterSuccess = sysUserService.registerSysUser(sysUser);
        if(isRegisterSuccess){
            model = ResultModel.success("注册成功", "登录", "/login", model);
        }else {
            model = ResultModel.fail("用户已存在", "注册", "/register", model);
        }
        return "common/tip";
    }

}
